<template>
  <div class="daochu_wrap">
    <div class="daochu_type">
      <div class="type_title">导出类型:</div>
      <div class="type_ipt">
        <el-radio-group class="bin_radio" v-model="daochuType" @change="aaa()">
          <el-radio :label="'1'">本地</el-radio>
          <el-radio :label="'2'">数据库</el-radio>
        </el-radio-group>
      </div>
    </div>
    <div class="daochu_shujuku_wrap" v-if="daochuType === '2'">
      <div class="daochu_shujuku_type">
        <div class="type_title">导出到:</div>
        <div class="type_ipt">
          <el-radio-group
            class="bin_radio"
            :disabled="notChange"
            v-model="daochuShujukuType"
          >
            <el-radio :label="'1'">现有表单</el-radio>
            <el-radio :label="'2'">新建表单</el-radio>
          </el-radio-group>
        </div>
      </div>
      <div class="daochu_shujuku_main">
        <div class="shujuku_tree_title">现有表单:</div>
        <div class="shujuku_tree_wrap">
          <div class="bin_tree_main">
            <el-tree
              class="bin_tree"
              :props="defaultProps"
              :load="loadNodeFn"
              @node-click="shujutreeNodeClickFn"
              lazy
            >
              <div class="custom-tree-node" slot-scope="{ node, data }">
                <div class="custom_title">{{ node.label }}</div>
                <div
                  class="custom_btns"
                  v-show="daochuShujukuType === '2' && node.level === 2"
                >
                  <el-button
                    type="text"
                    size="mini"
                    class="bin_button"
                    icon="el-icon-circle-plus"
                    @click="appendTreeNodeFn(data)"
                  >
                    新建
                  </el-button>
                </div>
              </div>
            </el-tree>
          </div>
        </div>
      </div>
    </div>
    <div class="daochu_btns">
      <el-button type="primary" class="bin_button" @click="close">
        取消
      </el-button>
      <el-button type="primary" class="bin_button" @click="daochuSubmitFn">
        开始导出
      </el-button>
    </div>
  </div>
</template>

<script>
import { fileDaoChuUtils } from "../utils/utils.js";
export default {
  name: "MyComponent",
  props: {
    // 需要导出的表中选择的数据
    selected: {
      type: Array,
      default: () => {
        return [];
      },
    },
    daoruTableId: {
      type: String,
      default: "",
    },
    rongheTableId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      notChange: false,
      // 导出类型 1 本地 2 数据库
      daochuType: "1",
      // 导出数据库类型 1 现有表单 2 新建表单
      daochuShujukuType: "1",
      defaultProps: {
        children: "dataTypeVoList",
        label: "dataTypeName",
        isLeaf: "leaf",
      },
      createnew: false,
    };
  },
  methods: {
    aaa() {
      this.daochuShujukuType = "1";
      this.notChange = false;
    },
    // 融合的导出 （本地和数据库）
    async daochuSubmitFn() {
      // 融合的导出  - 本地
      if (this.daochuType === "1") {
        let blobRes = await this.$api.rongheDownloadData({
          importDataTableId: this.daoruTableId
            ? this.daoruTableId
            : this.rongheTableId,
          dataIds: this.selected,
        });
        fileDaoChuUtils(blobRes, "融合数据导出表.xlsx");
        this.$message({
          message: "导出成功",
          type: "success",
        });
        this.$emit("close");
      } else if (this.daochuType === "2") {
        if (this.daochuShujukuType === "1") {
          await this.ysjtqDaochuZhaiquShujuGoBiaoDataFn();
        } else if (this.daochuShujukuType === "2") {
          await this.ysjtqDaochuZhaiquShujuGoNewBiaoDataFn();
        }
      }
    },
    // 融合导出结果到现有表单
    async ysjtqDaochuZhaiquShujuGoBiaoDataFn() {
      if (this.currentTreeItem) {
        let data = {
          exportTableId: this.rongheTableId,
          importTableId: this.currentTreeItem.dataTableId,
          dataIds: this.selected,
          operationType: 2, //操作类型，1-元数据摘取、2-筛选融合、3-关联判证、4-原始数据导入
          // isCreated: 1, //是现有还是创建 1-现有表单、2-创建新表单
          isCreated: this.createnew ? "2" : "1",
        };
        let res = await this.$api.rongheExportToDatabase(data);
        if (res.code === 200) {
          this.$message({
            message: res.result,
            type: "success",
          });
          this.$emit("close");
        }
      } else {
        this.$message({
          message: "请先选择并确认导入的表~",
          type: "warning",
        });
      }
    },
    // 融合结果导出到新表
    async ysjtqDaochuZhaiquShujuGoNewBiaoDataFn() {
      if (this.currentTreeItem) {
        let data = {
          exportTableId: this.rongheTableId,
          dataIds: this.selected,
          operationType: 2, //操作类型，1-元数据摘取、2-筛选融合、3-关联判证、4-原始数据导入
          // isCreated: 2, //是现有还是创建 1-现有表单、2-创建新表单
          isCreated: this.createnew ? "2" : "1",
          tableName: this.currentTreeItem.dataTypeName, //新建表单时需要传表名
          dataTypeId: this.currentTreeItem.dataTypeId, //数据类型，左侧树中对应的该表的类型
          databaseType: this.currentTreeItem.databaseType, //数据库类型，左侧树中对应的该表的类型
        };
        let res = await this.$api.rongheExportToDatabase(data);
        if (res.code === 200) {
          this.$message({
            message: res.result,
            type: "success",
          });
          this.$emit("close");
        }
      } else {
        this.$message({
          message: "请先选择并确认导入的表~",
          type: "warning",
        });
      }
    },
    // 取消导出
    close() {
      this.$emit("close");
    },
    // 新建表
    appendTreeNodeFn(data) {
      this.$prompt("请输入新建的文件夹名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^.+$/,
        inputErrorMessage: "新建的文件夹名称不能为空~",
      })
        .then(({ value }) => {
          this.notChange = true;
          const newChild = {
            id: new Date().getTime(),
            dataTypeName: value,
            databaseType: data.databaseType,
            dataTypeId: data.dataTypeId,
            leaf: true,
            create: true,
          };
          if (!data.dataTypeVoList) {
            this.$set(data, "dataTypeVoList", []);
          }
          data.dataTypeVoList.push(newChild);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
    // 树节点点击事件
    shujutreeNodeClickFn(data, node) {
      // 选择的表的那一层
      // console.log(this.daochuShujukuType, "this.daochuShujukuType");
      if (node.level === 3) {
        this.currentTreeItem = data;
        if (data.create) {
          this.createnew = data.create;
        } else {
          this.createnew = false;
        }
      } else {
        this.currentTreeItem = null;
      }
    },
    /**
     * tree 树组件 的懒加载
     * @param {*} node
     * @param {*} resolve
     */
    async loadNodeFn(node, resolve) {
      if (node.level === 0) {
        // 获取第一级数据
        await this.ysjtqGetDaochuShujukuTree1Fn();
        return resolve(this.shujukuTreeData);
      } else if (node.level === 1) {
        // 直接返回第二级数据
        return resolve(node.data.dataTypeVoList);
      } else if (node.level === 2) {
        // 获取第三级数据
        let list = await this.ysjtqGetDaochuShujukuTree2Fn(
          node.data.databaseType,
          node.data.dataTypeId
        );
        return resolve(list);
      }
    },
    /**
     * 获取树的结构 前两层
     */
    async ysjtqGetDaochuShujukuTree1Fn() {
      let res = await this.$api.ysjtqGetFileTypeApi(2);
      this.shujukuTreeData = res.result.map((item) => {
        return {
          ...item,
          dataTypeName: item.databaseTypeName,
          databaseType: item.databaseType,
        };
      });
    },
    /**
     * 获取树的结构 第三层
     * @param {String} databaseType 数据库类型
     * @param {String} dataTypeId 数据库类型的id
     */
    async ysjtqGetDaochuShujukuTree2Fn(databaseType, dataTypeId) {
      let params = {
        databaseType,
        dataTypeId,
      };
      let res = await this.$api.ysjtqGetDaochuShujukuTree2Api(params);
      return res.result.map((item) => {
        return {
          ...item,
          dataTypeName: item.dataTableName,
          databaseType: item.databaseType,
          leaf: true,
        };
      });
    },
  },
  created() {
    // Component created
  },
  mounted() {
    // Component mounted
  },
  updated() {
    // Component updated
  },
  destroyed() {
    // Component destroyed
  },
};
</script>

<style lang="scss" scoped>
.daochu_wrap {
  .daochu_type,
  .daochu_shujuku_type {
    display: flex;
    align-items: center;
    margin-bottom: 32px;
    .type_title {
      font-size: 18px;
      color: #fff;
      width: 110px;
    }
  }
  .daochu_shujuku_wrap {
    .daochu_shujuku_main {
      display: flex;
      .shujuku_tree_title {
        flex: 0 0 auto;
        font-size: 18px;
        color: #fff;
        width: 110px;
      }
      .shujuku_tree_wrap {
        flex: 1 1 auto;
        width: 0;
        height: 340px;
        border: 1px solid #02fff4;
        overflow: hidden;
        padding: 20px;
        .bin_tree_main {
          width: 100%;
          height: 100%;
          overflow: auto;
        }
      }
    }
  }
  .daochu_btns {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 70px;
  }
}
</style>
